const Comment = require('../models/Comment');
const CampusNotice = require('../models/CampusNotice');
const HotTopic = require('../models/HotTopic');
const Activity = require('../models/Activity');
const MarketItem = require('../models/MarketItem');
const { createNotification } = require('./notificationController');

// 辅助函数：获取目标类型的中文名称
function getTargetTypeName(type) {
    const typeNames = {
        notice: '通知',
        topic: '话题',
        activity: '活动',
        market: '商品',
        post: '帖子'
    };
    return typeNames[type] || '内容';
}

// 添加评论
exports.addComment = async (req, res) => {
    try {
        const { content, targetType, targetId, parentId } = req.body;

        // 验证评论内容
        if (!content) {
            return res.status(400).json({ message: '评论内容不能为空' });
        }

        // 验证目标信息
        if (!targetType || !targetId) {
            return res.status(400).json({ message: '评论目标信息不完整' });
        }

        // 验证用户信息
        if (!req.user || !req.user.id) {
            return res.status(401).json({ message: '用户未认证或信息缺失' });
        }

        // 选择目标模型
        let targetModel;
        switch (targetType) {
            case 'notice':
                targetModel = CampusNotice;
                break;
            case 'topic':
                targetModel = HotTopic;
                break;
            case 'activity':
                targetModel = Activity;
                break;
            case 'market':
                targetModel = MarketItem;
                break;
            default:
                return res.status(400).json({ message: '无效的评论目标类型' });
        }

        // 验证目标内容并获取所有者信息
        const target = await targetModel.findById(targetId);
        if (!target) {
            return res.status(404).json({ message: '评论目标不存在' });
        }

        // 验证父评论
        if (parentId) {
            const parentComment = await Comment.findById(parentId);
            if (!parentComment) {
                return res.status(404).json({ message: '被回复的评论不存在' });
            }
        }

        // 创建评论
        const comment = await Comment.create({
            content,
            userId: req.user.id,
            targetType,
            targetId,
            parentId
        });

        // 发送通知
        // 如果是回复评论,则通知原评论作者
        if (parentId) {
            const parentComment = await Comment.findById(parentId).populate('userId');
            if (parentComment && parentComment.userId._id.toString() !== req.user.id) {
                await createNotification({
                    recipient: parentComment.userId._id,
                    sender: req.user.id,
                    type: 'reply',
                    targetType,
                    targetId,
                    targetModel: targetModel.modelName,
                    commentId: comment._id,
                    content: `${req.user.username} 回复了您的评论: ${content.substring(0, 50)}...`
                });
            }
        }
        // 如果不是回复且目标内容有所有者,则通知内容所有者
        else if (target.userId && target.userId.toString() !== req.user.id) {
            await createNotification({
                recipient: target.userId,
                sender: req.user.id,
                type: 'comment',
                targetType,
                targetId,
                targetModel: targetModel.modelName,
                commentId: comment._id,
                content: `${req.user.username} 评论了您的${getTargetTypeName(targetType)}: ${content.substring(0, 50)}...`
            });
        }

        // 返回评论数据
        const populatedComment = await Comment.findById(comment._id)
            .populate('userId', 'username avatar')
            .populate('parentId');

        res.status(201).json({
            code: 200,
            data: populatedComment,
            message: '评论发表成功'
        });
    } catch (error) {
        console.error('添加评论失败:', error);
        res.status(500).json({ message: '添加评论失败，请稍后重试' });
    }
};

// 根据目标获取评论列表
exports.getCommentsByTarget = async (req, res) => {
    try {
        const { targetType, targetId } = req.params;

        // 获取一级评论
        const comments = await Comment.find({
            targetType,
            targetId,
            parentId: null
        })
        .populate('userId', 'username avatar')
        .sort('-createdAt');

        // 获取每个一级评论的回复
        const commentsWithReplies = await Promise.all(
            comments.map(async (comment) => {
                const replies = await Comment.find({
                    parentId: comment._id
                })
                .populate('userId', 'username avatar')
                .sort('createdAt');

                const commentObj = comment.toObject();
                commentObj.replies = replies;
                return commentObj;
            })
        );

        res.json({
            code: 200,
            data: commentsWithReplies,
            message: '获取评论成功'
        });
    } catch (error) {
        console.error('获取评论失败:', error);
        res.status(500).json({ message: '获取评论失败，请稍后重试' });
    }
};

// 获取评论的回复列表
exports.getReplies = async (req, res) => {
    try {
        const { commentId } = req.params;

        const replies = await Comment.find({
            parentId: commentId
        })
        .populate('userId', 'username avatar')
        .sort('createdAt');

        res.json({
            code: 200,
            data: replies,
            message: '获取回复成功'
        });
    } catch (error) {
        console.error('获取回复失败:', error);
        res.status(500).json({ message: '获取回复失败，请稍后重试' });
    }
};

// 删除评论
exports.deleteComment = async (req, res) => {
    try {
        const { commentId } = req.params;
        const comment = await Comment.findById(commentId);

        if (!comment) {
            return res.status(404).json({ message: '评论不存在' });
        }

        // 验证用户权限
        if (comment.userId.toString() !== req.user.id && req.user.role !== 'admin') {
            return res.status(403).json({ message: '无权删除此评论' });
        }

        // 删除评论及其所有回复
        await Promise.all([
            Comment.deleteOne({ _id: commentId }),
            Comment.deleteMany({ parentId: commentId })
        ]);

        res.json({
            code: 200,
            message: '评论删除成功'
        });
    } catch (error) {
        console.error('删除评论失败:', error);
        res.status(500).json({ message: '删除评论失败，请稍后重试' });
    }
};
